/**
 *
 */
package edu.uwm.nlp.jude.internal;

import java.io.IOException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.SimpleAnalyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Searcher;
import org.apache.lucene.search.TopDocCollector;
import org.apache.lucene.search.TopDocs;

import util.StringUtil;

/**
 * @author qing
 *
 * Apr 21, 2009
 */
public class PMIDFinder {
    
//    String indexFile = "/home/data_user/pubmed/indexbak";
    IndexSearcher searcher = null;
    QueryParser parser=new QueryParser("title",new StandardAnalyzer());
    
//    String indexFile = "z:/pubmed/indexbak";
    public PMIDFinder()
    {
        
    }
    
    public PMIDFinder(String indexPath) throws CorruptIndexException, IOException
    {
    	searcher=new IndexSearcher(indexPath);
    }
    
    public String replaceSymbolAsSpace(String s){
    	if(s==null)
    		return "";
    	StringBuilder strb=new StringBuilder();
    	for(int i=0;i<s.length();i++){
    		char c=s.charAt(i);
    		if(Character.isLetterOrDigit(c))
    			strb.append(c);
    		else
    			strb.append(' ');
    	}
    	return strb.toString();
    }
    
    public String findPMID(String title, String source, String year)
    {
        String id = null;
        try {
        	title=replaceSymbolAsSpace(title).trim();
            source = replaceSymbolAsSpace(source).trim();
            year = replaceSymbolAsSpace(year).trim();
            if(title.length()+source.length()+year.length()==0){
            	return id;
            }
            Query query = parser.parse((title.length()>0?("title:"+title):"")+
            		(source.length()>0?(" journalTitle:"+source):"")+
            				(year.length()>0?(" date:"+year):""));
            TopDocs hits = searcher.search(query, null, 1);
            ScoreDoc[] docs = hits.scoreDocs;
            if(docs.length>0)
            {Document doc=searcher.getIndexReader().document(docs[0].doc);
            id = doc.get("id");
            }
            return id;
            
        } catch (CorruptIndexException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    public static void main(String[] args)
    {
        PMIDFinder finder = new PMIDFinder();
        String id = finder.findPMID(args[0], args[1], args[2]);
        System.out.println("id="+id);
    }

}


